package com.henry.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.henry.entity.User;
import com.henry.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Henry
 * @since 2020-06-28
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/list")
    public Object list(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.ge("id",1);
        wrapper.le("id",4);
        List<User> userList = userMapper.selectList(wrapper);
        return userList;
    }

    @RequestMapping("/page")
    public Object page(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "2") Integer pageSize){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        Page<User> page = new Page(pageNum,pageSize);
        Page<User> userPage = userMapper.selectPage(page, wrapper);
        return userPage;
    }

    @RequestMapping("/add")
    public Object add(@RequestParam String name,@RequestParam(defaultValue = "20") Integer age){
        User user = new User();
        user.setName(name);
        user.setAge(age);
        userMapper.insert(user);
        return user;
    }

    @Transactional
    @RequestMapping("/addError")
    public Object addEoor(){
        Random random = new Random();
        User user = new User();
        user.setName("zzz"+random.nextInt(100));
        user.setAge(random.nextInt(100));
        userMapper.insert(user);
        int k=2/0;
        user = new User();
        user.setName("kkk"+random.nextInt(100));
        user.setAge(random.nextInt(100));
        userMapper.insert(user);

        return user;
    }

    @RequestMapping("/even")
    public Object even(){
        List<User> userList = userMapper.selectListByEvenId();
        return userList;
    }

    @RequestMapping("/odd")
    public Object odd(){
        List<User> userList = userMapper.selectListByOddId();
        return userList;
    }

    @RequestMapping("/selectAll")
    public Object selectAll(){
        List<User> userList = userMapper.selectAll(new QueryWrapper());
        return userList;
    }

}
